package com.woniuxy.mapper.impl;

import com.woniuxy.mapper.StuDao;
import com.woniuxy.entity.Stu;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 作者
 * @create 2025-08-12 9:38
 */
public class StuDaoImpl implements StuDao {
    QueryRunner queryRunner;

    @Override
    public void insert(Stu stu) throws SQLException, ClassNotFoundException {
        queryRunner=new QueryRunner();
        String sql="insert into stu values(?,?,?,?)";
        Object[] obj={stu.getSid(),stu.getSname(),stu.getPassword(),stu.getAge()};
        queryRunner.update(JdbcUtil.getConnection(), sql,obj);

    }

    @Override
    public void update(Stu stu) throws SQLException, ClassNotFoundException {
        queryRunner=new QueryRunner();
        Connection connection = JdbcUtil.getConnection();
        String sql="update stu set sname=?,password=?,age=? where sid=?";
        Object[] obj={stu.getSname(),stu.getPassword(),stu.getAge(),stu.getSid(),};
        queryRunner.update(connection, sql, obj);
    }

    @Override
    public void deleteBySid(int sid) throws SQLException, ClassNotFoundException {

    }

    @Override
    public Stu selectBySid(int sid) throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        queryRunner=new QueryRunner();
        Stu stu = queryRunner.query(JdbcUtil.getConnection(), "select * from stu where sid=?",
                new BeanHandler<Stu>(Stu.class), sid);
        return stu;
    }

    @Override
    public List<Stu> selectAll() throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        queryRunner=new QueryRunner();
        List<Stu> stus = queryRunner.query(JdbcUtil.getConnection(), "select * from stu",
                new BeanListHandler<Stu>(Stu.class));
        return stus;
    }

    @Override
    public List<Stu> selectBySname(String sname) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        return List.of();
    }
}
